package com.chenxi.vhr.controller.system.basic;

import com.chenxi.vhr.bean.BaseRole;
import com.chenxi.vhr.bean.common.Result;
import com.chenxi.vhr.bean.form.BaseMenuRoleEditForm;
import com.chenxi.vhr.service.BaseMenuService;
import com.chenxi.vhr.service.BaseRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author : zhangchenxi
 * @create : 2022-02-06
 **/
@RestController
@RequestMapping("/system/basic/permission")
public class PermissionController  {

    @Autowired
    BaseRoleService roleService;

    @Autowired
    BaseMenuService menuService;

    @GetMapping("/roleList")
    public Result getAllRole() {
        return Result.ok("角色信息加载成功", roleService.list());
    }

    @GetMapping("/menuTreeList")
    public Result getMenuTree() {
        return Result.ok("菜单树加载成功", menuService.getMenuTree());
    }

    /**
     * 初始化菜单和菜单的选中情况
     * @return
     */
    @GetMapping("/menuTreeList/{roleId}")
    public Result getMenuTreeExt(@PathVariable Integer roleId) {
        return Result.ok("菜单树相关信息加载成功", menuService.loadMenuTreeMapInfo(roleId));
    }

    @PutMapping("/")
    public Result updateRoleMenuListByRoleId(@RequestBody BaseMenuRoleEditForm form) {
        boolean updateFlag = menuService.updateMenuListByRoleId(form.getRoleId(), form.getMenuIdList());
        if (updateFlag) {
            return Result.ok("更新成功");
        } else {
            return Result.error("更新失败");
        }
    }

    @PostMapping("/")
    public Result addRole(@RequestBody BaseRole role) throws Exception {
        if (role != null && !role.getName().startsWith("ROLE_")) {
            throw new Exception("非法的英文角色名称！");
        }
        return roleService.save(role) ? Result.ok("添加成功！"): Result.error("添加失败！");
    }

    @DeleteMapping("/{roleId}")
    public Result deleteRole(@PathVariable Integer roleId) throws Exception{
        if (menuService.countMenuByRoleId(roleId) > 0) {
            throw new Exception("当前角色存在关联权限，无法删除！");
        }
        return roleService.removeById(roleId) ? Result.ok("删除成功！"): Result.error("删除失败！");
    }

}
